package com.yesep.downstream;

import com.yesep.constant.Constants;
import com.yesep.handler.MessageHandler;
import com.yesep.model.MessageBaseModel;
import com.yesep.netty.NettyChannelManager;
import io.netty.channel.Channel;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Objects;

/**
 * @program: gateway
 * @description: 下行任务
 * @author: quliang
 * @create: 2019-07-14 12:23
 **/
public class DownStreamDataTask implements Runnable {

    private static Logger logger = LoggerFactory.getLogger(DownStreamDataThread.class);

    private MessageBaseModel data;

    DownStreamDataTask(MessageBaseModel data) {
        this.data = data;
    }


    @Override
    public void run() {
        try {
            if (data == null) {
                return;
            }
            String mn = data.getIp();
            if (Objects.equals(mn, null)) return;

            Channel channel = NettyChannelManager.getInstance().getChannelByMn(mn);
            if (Objects.equals(channel, null)) {
                logger.error("[DownStreamDataTask] 未找到[{}][{}] 对应的Channel!", mn, data);
                return;
            }
            //响应报文
            String responseMessage = MessageHandler.tranMessageModelToString(data, Constants.CMD_MESSAGE_TEMPLATE_MAP.get(Constants.UP_TO_DOWN_RESPONSE_CN));

            // 给下位机送回复命令
            channel.writeAndFlush(responseMessage);

            logger.info("[DownStreamDataTask][下行报文][mn={}]({})({})][{}]", mn, channel.id().asLongText(), channel.remoteAddress().toString(), data);

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }
}
